package com.eu.ebpm.engine.deploy;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.entity.args.Param;
import com.eu.ebpm.engine.entity.deploy.Position;
import com.eu.ebpm.engine.entity.history.HisExecution;
import com.eu.ebpm.engine.exception.WorkFlowException;
import com.eu.ebpm.engine.repository.HisExecutionRepository;
import com.eu.ebpm.engine.repository.HisTaskRepository;

@Component
public class PositionService {
	
	@Autowired
	private HisExecutionRepository hisExecutionRepository;
	@Autowired
	private HisTaskRepository hisTaskRepository;
	
	public List<Position> getHisTaskPositions(String businessKey) {
		List<HisExecution> hisExecutions = hisExecutionRepository.list(Param.init("businessKey", businessKey).put("runStatus", false));
		HisExecution hisExecution = null;
		for(HisExecution h : hisExecutions) {
			if(h.getParentId() == 0) {
				hisExecution = h;
				break;
			}
		}
		
		if(hisExecution == null) throw new WorkFlowException("业务号[" + businessKey + "]查询不到对应的root流程");
		
		List<Position> positions = new ArrayList<Position>();
		List<Long> hisExecutionIds = new ArrayList<Long>();
		findHisExecutionIds(hisExecutionIds, hisExecution.getId());
		
//		List<HisTask> hisTasks = hisTaskRepository.listHisTask(Param.map("executionIds", hisExecutionIds));
//		for(HisTask t : hisTasks) {
//			positions.add(DefinitionsCache.getPosition(t.getMissionId()));
//		}
		return positions;
	}

	private void findHisExecutionIds(List<Long> hisExeIds, long id) {
		hisExeIds.add(id);
		List<HisExecution> hisExecutions = hisExecutionRepository.list(Param.map("parentId", id));
		for(HisExecution he : hisExecutions) {
			findHisExecutionIds(hisExeIds, he.getId());
		}
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
